﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace SpotifyHUD
{
    public static class SpotiftyControler
    {
        private static Process SpotifyProcess { get; set; }

        static SpotiftyControler()
        {
            var processes = Process.GetProcessesByName("spotify");
            SpotifyProcess = (processes.Length > 0 ? processes.First() : null);
        }

        public static void Next()
        {
            PostMessage(0xB0000L);
        }

        public static void Prev()
        {
            PostMessage(0xC0000L);
        }

        public static void Play()
        {
            PostMessage(0xE0000L);
        }

        private static void PostMessage(Int64 param)
        {
            var hdl = SpotifyProcess.MainWindowHandle;
            if (hdl.ToInt64() > 0)
            {
                User32.PostMessage(SpotifyProcess.MainWindowHandle, 0x319, IntPtr.Zero, new IntPtr(param));
            }
        }

        public static string GetNowplaying()
        {
            var hdl = SpotifyProcess.MainWindowHandle;
            if (hdl.ToInt64() > 0)
            {
                var lpText = new String(' ',500);
                if (User32.GetWindowText(hdl, lpText, 500) > 0)
                {
                    var begin = "Spotify - ";
                    if (lpText.StartsWith(begin))
                        lpText = lpText.Substring(begin.Length);
                    return lpText.ToString();
                }
            }
            return "Spotify Closed";
        }
    }
}
